package com.lh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lh.commonutils.R;
import com.lh.dao.EduChapterMapper;
import com.lh.dao.EduCourseDescriptionMapper;
import com.lh.dao.EduVideoMapper;
import com.lh.entity.EduChapter;
import com.lh.entity.EduCourse;
import com.lh.dao.EduCourseMapper;
import com.lh.entity.EduCourseDescription;
import com.lh.entity.EduVideo;

import com.lh.entity.frontvo.CourseWebVo;
import com.lh.entity.vo.CourseInfoVo;
import com.lh.entity.vo.CoursePublishVo;
import com.lh.entity.vo.CourseQuery;
import com.lh.entity.frontvo.CourseQueryVo;


import com.lh.feign.VodFeign;
import com.lh.service.IEduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


import javax.annotation.Resource;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author yms
 * @since 2021-06-05
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements IEduCourseService {


    @Resource
    private EduCourseMapper courseMapper;
    @Resource
    private EduCourseDescriptionMapper eduCourseDescriptionMapper;
    @Resource
    private EduVideoMapper videoMapper;
    @Resource
    private EduChapterMapper chapterMapper;
    @Resource
    private VodFeign vodFeign;

    private final String StatusDraft="Draft";
    private final String StatusNormal="Normal";
    /**
     * 添加课程
     *
     * @param courseInfoVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveCourseInfo(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        int insert = courseMapper.insert(eduCourse);

        if (insert == 0) {
            return R.error().message("添加课程失败");
        }
        String id = eduCourse.getId();
        EduCourseDescription description = new EduCourseDescription();
        description.setDescription(courseInfoVo.getDescription());
        description.setId(id);
        int insert1 = eduCourseDescriptionMapper.insert(description);
        if (insert1 == 0) {
            return R.error().message("添加课程失败");
        }
        return R.ok().message("添加课程成功").data("courseId", id);
    }

    /**
     * 根据课程id 查询
     *
     * @param courseId
     * @return
     */
    @Override
    public R getCourseInfo(String courseId) {

        EduCourse eduCourse = courseMapper.selectById(courseId);
        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(eduCourse, courseInfoVo);
        EduCourseDescription eduCourseDescription = eduCourseDescriptionMapper.selectById(courseId);
        courseInfoVo.setDescription(eduCourseDescription.getDescription());

        return R.ok().data("courseInfoVo", courseInfoVo);
    }

    /**
     * 修改课程基本信息
     *
     * @param courseInfoVo
     * @return
     */
    @Override
    public R updateCourseInfo(CourseInfoVo courseInfoVo) {
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo, eduCourse);
        int update = courseMapper.updateById(eduCourse);
        if (update == 0) {
            return R.error().message("修改失败");
        }
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        eduCourseDescription.setId(courseInfoVo.getId());
        eduCourseDescription.setDescription(courseInfoVo.getDescription());
        int i = eduCourseDescriptionMapper.updateById(eduCourseDescription);
        if (i == 0) {
            return R.error().message("修改失败");
        }

        return R.ok().message("修改成功");
    }

    /**
     * 根据课程id查询课程确定信息
     *
     * @param id
     * @return
     */
    @Override
    public R getPublishCourseInfo(String id) {
        CoursePublishVo publishCourseInfo = courseMapper.getPublishCourseInfo(id);

        return R.ok().data("CoursePublishVo", publishCourseInfo);
    }

    /**
     * 修改课程状态
     *
     * @param id
     * @return
     */
    @Override
    public R publishCourse(String id) {
        EduCourse course = courseMapper.selectById(id);
        String status = course.getStatus();
        EduCourse eduCourse = new EduCourse();
        if (status.equals(StatusNormal)){
            eduCourse.setId(id);
            eduCourse.setStatus(StatusDraft);
        }else {
            eduCourse.setId(id);
            eduCourse.setStatus(StatusNormal);
        }

        int i = courseMapper.updateById(eduCourse);
        if (i > 0) {
            return R.ok();
        } else {
            return R.error();
        }

    }

    /**
     * 根据id查询所有信息
     *
     * @param
     * @param
     * @param courseQuery
     * @return
     */
    @Override
    public void findAllCourse(Page<EduCourse> coursePage, CourseQuery courseQuery) {

        LambdaQueryWrapper<EduCourse> wrapper = new LambdaQueryWrapper<>();
        if (courseQuery == null) {

            courseMapper.selectPage(coursePage, wrapper);
        }
        String teacherId = courseQuery.getTeacherId();
        String title = courseQuery.getTitle();
        String status = courseQuery.getStatus();

        if(!StringUtils.isEmpty(teacherId)){
            wrapper.eq(EduCourse::getTeacherId,teacherId);
        }
        if (!StringUtils.isEmpty(title)) {
            wrapper.eq(EduCourse::getTitle, title);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq(EduCourse::getStatus, status);
        }
        wrapper.orderByDesc(EduCourse::getGmtCreate);
        baseMapper.selectPage(coursePage, wrapper);

    }

    /**
     * 根据id删除 小节，章节，描述，课程
     *
     * @param id
     * @return
     */
    @Override
    @Transactional()
    public R deleteById(String id) {


        //1删除小节
        LambdaQueryWrapper<EduVideo> videoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videoLambdaQueryWrapper.eq(EduVideo::getCourseId, id);
        List<EduVideo> eduVideos = videoMapper.selectList(videoLambdaQueryWrapper);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < eduVideos.size(); i++) {
            String videoSourceId = eduVideos.get(i).getVideoSourceId();
            if (!StringUtils.isEmpty(videoSourceId)){
                list.add(videoSourceId);
            }
        }
        if (list.size()>0){
            vodFeign.deleteBatch(list);
        }
        videoMapper.delete(videoLambdaQueryWrapper);
        //2删除章节
        LambdaQueryWrapper<EduChapter> eduChapterLambdaQueryWrapper = new LambdaQueryWrapper<>();
        eduChapterLambdaQueryWrapper.eq(EduChapter::getCourseId, id);
        chapterMapper.delete(eduChapterLambdaQueryWrapper);
        //3删除描述
        eduCourseDescriptionMapper.deleteById(id);
        //4删除课程
        int i = courseMapper.deleteById(id);
        if (i > 0) {
            return R.ok();
        } else {
            return R.error();
        }

    }

    /**
     * 根据讲师id查询当前讲师的课程列表
     *
     * @param teacherId
     * @return
     */
    @Override
    public List<EduCourse> selectByTeacherId(String teacherId) {
        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<EduCourse>();
        queryWrapper.eq("status","Normal");
        queryWrapper.eq("teacher_id", teacherId);
        //按照最后更新时间倒序排列
        queryWrapper.orderByDesc("gmt_modified");

        List<EduCourse> courses = baseMapper.selectList(queryWrapper);
        return courses;
    }

    @Override
    public Map<String, Object> pageListWeb(Page<EduCourse> pageParam, CourseQueryVo courseQuery) {

        QueryWrapper<EduCourse> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(courseQuery.getSubjectParentId())) {
            queryWrapper.eq("subject_parent_id", courseQuery.getSubjectParentId());
        }

        if (!StringUtils.isEmpty(courseQuery.getSubjectId())) {
            queryWrapper.eq("subject_id", courseQuery.getSubjectId());
        }

        if (!StringUtils.isEmpty(courseQuery.getBuyCountSort())) {
            queryWrapper.orderByDesc("buy_count");
        }

        if (!StringUtils.isEmpty(courseQuery.getGmtCreateSort())) {
            queryWrapper.orderByDesc("gmt_create");
        }

        if (!StringUtils.isEmpty(courseQuery.getPriceSort())) {
            queryWrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageParam, queryWrapper);

        List<EduCourse> records = pageParam.getRecords();
        long current = pageParam.getCurrent();
        long pages = pageParam.getPages();
        long size = pageParam.getSize();
        long total = pageParam.getTotal();
        boolean hasNext = pageParam.hasNext();
        boolean hasPrevious = pageParam.hasPrevious();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        return map;

    }

    @Override
    public CourseWebVo selectInfoWebById(String id) {
        this.updatePageViewCount(id);
        return baseMapper.selectInfoWebById(id);
    }

    @Override
    public void updatePageViewCount(String id) {
        System.out.println("=-========================"+id);
        EduCourse course = baseMapper.selectById(id);
        course.setViewCount(course.getViewCount() + 1);
        baseMapper.updateById(course);
    }

    /**
     * 每天课程浏览量
     *
     * @param day
     * @return
     */
    @Override
    public Integer countCourse(String day) {
      Integer countCourse= baseMapper.countCourse(day);
        return countCourse;
    }
}
